package sui.utils.http;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.apache.http.impl.client.DefaultHttpRequestRetryHandler;
import org.apache.http.impl.client.HttpClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyClient;
import org.jboss.resteasy.client.jaxrs.ResteasyClientBuilder;
import org.jboss.resteasy.client.jaxrs.ResteasyWebTarget;
import org.jboss.resteasy.client.jaxrs.engines.ApacheHttpClient4Engine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

/**
 * <p>
 * Description: restful 调用
 * </p>
 * @author XQF SUI
 * @created 2016年10月13日 下午3:42:23
 * @version 1.0
 */
public class RESTfulUtils {
	
	public static final String RESULT_FAIL_MESSAGE = "FAIL";

    private static Logger logger = LoggerFactory.getLogger(RESTfulUtils.class);

    public static String post(String uri, Object obj) {
        logger.info("RESTful POST请求, 地址:[ {} ], 参数:[ {} ]", uri, JSON.toJSONString(obj));
        return invoke(createRequest(createClient(), uri), initEntity(obj));
    }
    
    public static String get(String uri) {
        logger.info("RESTful GET请求, 地址:[ {} ]", uri);
        return invoke(createRequest(createClient(), uri));
    }
    
    private static String invoke(ResteasyWebTarget target, Entity<Object> entity) {
		return checkResponse(target.request().post(entity));
	}
    
    private static String invoke(ResteasyWebTarget target) {
    	return checkResponse(target.request().get());
    }

	private static String checkResponse(Response response) {
	    
        // TODO 此处只适用于本系统, 只有后端系统将所有异常都自己处理掉并一定返回信息, 才适用此逻辑, 否则需要自行根据状态码做逻辑处理
        if (response.getStatus() != 200) {
            logger.info("RESTful POST请求异常, HTTP error code:[ {} ]", response.getStatus());
            return RESULT_FAIL_MESSAGE;
        }
		
		return response.readEntity(String.class);
	}

	private static Entity<Object> initEntity(Object obj) {
		return Entity.entity(obj, MediaType.APPLICATION_JSON);
	}

	private static ResteasyWebTarget createRequest(ResteasyClient client, String url) {
		return client.target(url);
	}
	
	private static ResteasyClient createClient() {
        return new ResteasyClientBuilder()
                .httpEngine(new ApacheHttpClient4Engine(
                        HttpClientBuilder.create().setRetryHandler(new DefaultHttpRequestRetryHandler()).build(), true))
                .build();
    }
	
	public static void main(String[] args) {
	    String str = "{\"customerName\" : \"王五\", \"crm\" : \"111111\", \"mobile\" : \"135894768098\", \"customerSource\" : \"130\", \"sex\" : \"1\"}";
        System.out.println(post("http://10.100.138.125:9090/poseidon-web/services/customerService/saveOrUpdate/612/111", str));
    }
}
